package com.oocl.scan.handler;

import com.oocl.scan.jdt.parser.ModifierParser;
import com.oocl.scan.model.Component;
import com.oocl.scan.model.JavaClassElement;
import com.oocl.scan.model.Relationship;
import com.oocl.scan.utils.ScanConstants;
import com.oocl.scan.utils.StringUtil;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.NormalAnnotation;
import org.eclipse.jdt.core.dom.SingleMemberAnnotation;
import org.eclipse.jdt.core.dom.TypeDeclaration;

public class AjaxCallHandler extends BaseHandler{

  @Override
  public void handle(JavaClassElement element) {
    TypeDeclaration typeDeclaration = element.getTypeDeclaration();
    SingleMemberAnnotation classRequestMappingAnnotation = ModifierParser.getSingleMemberAnnotation(typeDeclaration, ScanConstants.ANNOTATION_REQUEST_MAPPING);
    if (classRequestMappingAnnotation != null) {
      String classRequestMappingURL = StringUtil.removeDoubleQuote(classRequestMappingAnnotation.getValue().toString());
      element.getMethodDeclarationList().forEach((methodDeclaration -> {
        String ajaxURL = getFullAjaxCallURL(methodDeclaration, classRequestMappingURL);
        if (ajaxURL != null) {
          String moduleName = element.getModuleName();
          Component component = new Component(ajaxURL, ScanConstants.AJAX_TYPE, moduleName, element.getDomainName());
          String toName = element.getJavaClassFullName() + "-" + methodDeclaration.getName().toString();
          Relationship relationship = new Relationship(ScanConstants.RELATION_TYPE_FLOWS, ajaxURL, moduleName, toName, moduleName);
          addToComponentStore(component);
          addToRelationshipStore(relationship);
        }
      }));
    }
  }

  private String getFullAjaxCallURL(MethodDeclaration methodDeclaration, String classRequestURL) {
    SingleMemberAnnotation methodRequestMappingAnnotation = ModifierParser
        .getSingleMemberAnnotation(methodDeclaration, ScanConstants.ANNOTATION_REQUEST_MAPPING);
    if (methodRequestMappingAnnotation != null) {
      String methodRequestMappingURL = StringUtil.removeDoubleQuote(methodRequestMappingAnnotation.getValue().toString());
      return classRequestURL + methodRequestMappingURL;
    }

    NormalAnnotation requestMapping = ModifierParser.getAnnotation(methodDeclaration, ScanConstants.ANNOTATION_REQUEST_MAPPING);
    if (requestMapping != null && ModifierParser.getAnnotationValueByName(requestMapping, "value") != null) {
      String methodRequestMappingURL = StringUtil.removeDoubleQuote(ModifierParser.getAnnotationValueByName(requestMapping, "value").toString());
      return classRequestURL + methodRequestMappingURL;
    }
    return null;
  }
}
